//
//  ViewController.swift
//  RAC-Swift-Demo
//
//  Created by LuckyStrike on 2018/7/25.
//  Copyright © 2018年 LuckyStrike. All rights reserved.
//

import UIKit

import UIKit
import ReactiveSwift
import ReactiveCocoa
import Result

class ViewController: UIViewController {
    
    @IBOutlet weak var emailField: UITextField!
    @IBOutlet weak var emailConfirmationField: UITextField!
    @IBOutlet weak var termsSwitch: UISwitch!
    @IBOutlet weak var reasonLabel: UILabel!
    @IBOutlet weak var submitButton: UIButton!
    
    fileprivate let userService : UserService = UserService()
    
    fileprivate var viewModel: ViewModel?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        viewModel = ViewModel(userService: userService)
        
        // Setup console messages.
        userService.requestSignal.observeValues {
            print("UserService.requestSignal: Username `\($0)`.")
        }
        
        viewModel!.submit.completed.observeValues {
            print("ViewModel.submit: execution producer has completed.")
        }
        
        viewModel!.email.result.signal.observeValues {
            print("ViewModel.email: Validation result - \($0 != nil ? "\($0!)" : "No validation has ever been performed.")")
        }
        
        viewModel!.emailConfirmation.result.signal.observeValues {
            print("ViewModel.emailConfirmation: Validation result - \($0 != nil ? "\($0!)" : "No validation has ever been performed.")")
        }
        
        
        // Initialize the interactive controls.
        emailField.text = viewModel!.email.value
        emailConfirmationField.text = viewModel!.emailConfirmation.value
        termsSwitch.isOn = false
        
        // Setup bindings with the interactive controls.
        viewModel!.email <~ emailField.reactive
            .continuousTextValues.skipNil()
        
        viewModel!.emailConfirmation <~ emailConfirmationField.reactive
            .continuousTextValues.skipNil()
        
        viewModel!.termsAccepted <~ termsSwitch.reactive
            .isOnValues
        
        // Setup bindings with the invalidation reason label.
        reasonLabel.reactive.text <~ viewModel!.reasons
        
        // Setup the Action binding with the submit button.
        submitButton.reactive.pressed = CocoaAction(viewModel!.submit)
    }
    
    
    
    //    required init?(coder aDecoder: NSCoder) {
    //        fatalError()
    //    }
}
